let XLSX = require('xlsx');
let fs = require('fs');
let Pinyin = require('pinyin-pro');

// 读取Excel文件
function readExcelFile(filePath) {
  let workbook = XLSX.readFile(filePath);
  let sheetName = workbook.SheetNames[1];
  let worksheet = workbook.Sheets[sheetName];
  return XLSX.utils.sheet_to_json(worksheet, { header: 1 });
}

function capitalizeFirstLetter(pinyinResult) {
  return pinyinResult.map(item => {
    // 处理 item 是数组还是字符串
    const syllables = Array.isArray(item) ? item : [item];

    return syllables.map(syllable => {
      return syllable.charAt(0).toUpperCase() + syllable.slice(1).toLowerCase();
    });
  });
}

function toPinyin(word) {
  // 获取数组形式不带声调的拼音
  let result = Pinyin.pinyin(word, { toneType: 'none', type: 'array' }); // ["han", "yu", "pin", "yin"]
  result = capitalizeFirstLetter(result);
  return result.flat().join('');
}

// 转换数据格式
function transformData(data) {
  return data.map(row => ({
    name: row[0].trim(),
    namePinyin: toPinyin(row[0].trim()),
    code: row[1],
    county: row[2] + '',
    pinyin: toPinyin(row[2] + ''),
  })).reduce((acc, item) => {
    let key = item.county;
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(item);
    return acc;
  }, {});
}

// 写入JSON文件
function writeJsonFile(data, outputFilePath) {
  let jsonData = JSON.stringify(data, null, 0);
  fs.writeFileSync(outputFilePath, jsonData, 'utf-8');
}

// 主函数
function main() {
  let inputFilePath = './济南红色围栏-新.xlsx'; // 替换为你的Excel文件路径
  let outputFilePath = './济南红色围栏-新.json';
  try {
    let excelData = readExcelFile(inputFilePath);
    let transformedData = transformData(excelData.slice(1)); // 忽略表头行
    writeJsonFile(transformedData, outputFilePath);
    console.log('转换完成，JSON文件已保存到', outputFilePath);
  } catch (error) {
    console.error('发生错误:', error);
  }
}

main();
